package com.douziit.meilianoa.base.config.filter;

import com.douziit.meilianoa.base.utils.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lh
 * @version 1.0
 * @Date 2018-04-16
 */
@Component
public class CrossDomainFilter implements Filter {

    @Value("${web.cross-domain}")
    private String domains;

    private static String ALLOW_HEADERS = "API-App-Id,API-User-ID,API-Oauth-Signature,API-Device-Name,API-Device-Type,API-Mobile-LOC" +
            ",API-User-Token,API-Push-Reg-Id,Content-Type,x-requested-with";

    public CrossDomainFilter() {
    }

    public CrossDomainFilter(String domains) {
        this.domains = domains;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filter) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (StrUtil.notBlank(domains)) {
            response.setHeader("Access-Control-Allow-Origin", domains);
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.setHeader("Access-Control-Allow-Headers", ALLOW_HEADERS);
        }
        filter.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
